package org.linlinjava.litemall.admin.web;

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.admin.constant.PermType;
import org.linlinjava.litemall.admin.vo.Json;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.SysPerm;
import org.linlinjava.litemall.db.service.LitemallSysPermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhy
 * @create 2018-10-08 10:30
 **/
@RestController
@RequestMapping("/admin/perm")
public class AdminSysPermController {
	private final Log logger = LogFactory.getLog(AdminSysPermController.class);

	@Autowired
	private LitemallSysPermService litemallSysPermService;

	@GetMapping("/list")
	public Object getlist(@LoginAdmin Integer adminId){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}
		String oper = "list menu,button,api permissions";
		List<SysPerm> list =litemallSysPermService.getList(PermType.MENU);
		if (list.isEmpty()){
			return ResponseUtil.ok(oper);
		}else{
			Map<Integer, List<SysPerm>> permMap = list.stream().collect(Collectors.groupingBy(SysPerm::getPtype));
			return ResponseUtil.ok(permMap);
		}
	}

	@PostMapping("/menu")
	public Object synMenuPermission (@RequestBody String body){
		String oper = "sync menu permission";
		List<SysPerm> notSyncedPerms = JSON.parseArray(body, SysPerm.class);
        if(!notSyncedPerms.isEmpty()){
	        litemallSysPermService.deleteByptype(PermType.MENU);
	        litemallSysPermService.saveOrUpdate(notSyncedPerms);
        }
        return ResponseUtil.ok(oper);
	}
}
